<?php

defined('SYSPATH') or die('No direct script access.');

/**
 * 消保数据修正
 */
class CLI_Shop_Promise extends CLI
{

    protected $_run_time = 60; // 估计运行间隔

    public function main() {
        try{
            $bench_start = microtime(TRUE);

            $protections = Shop_Promise::get_protections();
            $license_packet = $protections['license']['packet'];
            $original_packet = $protections['original']['packet'];

            DB::update('shops')
                ->set(array(
                    'protections' => $license_packet
                ))
                ->where('cert_type', '=', 2)
                ->execute();

            DB::update('shops')
                ->set(array(
                    'protections' => $original_packet
                ))
                ->where('cert_type', '=', 1)
                ->execute();

            $bench_end = microtime(TRUE);
            $eclipse_time = round($bench_end - $bench_start, 3);
            $log = "店铺消保修正 执行用时  {$eclipse_time} 秒.".date('Y-m-d H:i:s');
            CLI::output("\n" . $log);
        }
        catch(Exception $e)
        {
            DB::delete('cli_running')
                ->where('class', '=', get_class($this))
                ->execute();
            CLI::output("\n" . $e->getMessage());
        }
    }

    /**
     * 构造方法
     *
     * @param  CLI_Args  $args
     * @return void
     */
    public function __construct(CLI_Args $args = NULL)
    {

        $this->args = $args;
        if(DB::select('addtime')
            ->from('cli_running')
            ->where('class', '=', get_class($this))
            ->where('addtime', '>', time() - $this->_run_time)
            ->fetch_one())
        {
            CLI::output("\n 此分析器正在运行中");
            die();
        }
        else
        {
            $this->_runed = true;
            DB::insert('cli_running', array('class', 'addtime'))
                ->values(array(get_class($this), time()))
                ->execute();
        }
    }

    /**
     * 删除运行状态
     */
    public function  __destruct()
    {
        if($this->_runed)
        {
            DB::delete('cli_running')->where('class', '=', get_class($this))->execute();
        }
    }

}